//based on http://stackoverflow.com/questions/4025891/create-a-function-to-check-for-key-press-in-unix-using-ncurses
#include <ncurses/curses.h>
#include <unistd.h>  /* only for sleep() */

#include "kbd_thread.h"
#include "cpu.h"

int kbhit(void)
{
    int ch = getch();

    if (ch != ERR) {
        ungetch(ch);
        return 1;
    } else {
        return 0;
    }
}

void* kbd_thread(void* arg) {
  initscr();

  cbreak();
  noecho();
  
  nodelay(stdscr, 1);

  scrollok(stdscr, 1);
  

  while (1) {
    if (kbhit()) {
      char val = (char)getch();
      while(getch()!=ERR); //clear input
      printw("Key pressed! It was: %c\n", val);
      
      pthread_mutex_lock(&pending_interrupts_lock);
	  if(!keyboard_queue->empty(keyboard_queue)) {
			ready_queue->addToQ(ready_queue, keyboard_queue->dequeueFromQ(keyboard_queue));
			printw("Keyboard Process Filled!");
	  }
      pthread_mutex_unlock(&pending_interrupts_lock);
      
      if(val == 'q') {
        endwin();
        pthread_exit(NULL);
      }
      refresh();
    } else {
      refresh();
      usleep(0.1 * 1000*1000);
    }
  }
}

// int main(void) {
  
// }
